<template>
  <view class="cart" :style="{ paddingTop: `${getSystemInfo.navBarHeight}px` }">
    
    <navBar
      title="购物车"
      custom-back
      :class="isSubPage ? '' : 'nav-only-title'"
      :show-home="isSubPage"
      :show-back="isSubPage"
      @back="toBack"
      @home="toHome">
    </navBar>
    
    <view
      v-if="hasGoods"
      :class="['cart-content', isComponent && 'cart-component-content']"
      :style="{ height: `calc(100vh - ${getSystemInfo.navBarHeight}px)` }"
    >
      <!-- 购物车列表 -->
      <scroll-view class="list" scroll-y>
        <uni-swipe-action v-if="goodsList.length > 0">
          <uni-swipe-action-item v-for="(item, index) in goodsList" :key="item.goodsId">
            <!-- 列表显示内容 -->
            <view class="cart-item">
              <!-- 复选框 -->
              <view class="ci-checkbox">
                <u-checkbox-group v-model="item.checked" @change="onCheckItem(item.goodsId)">
                	<u-checkbox
                    :name="item.goodsId"
                    size="18px"
                    icon-size="14px"
                    shape="circle">
                  </u-checkbox>
                </u-checkbox-group>
              </view>
              <!-- 商品图片 -->
              <u--image v-if="item.goodsImges" width="88px" height="88px" :src="item.goodsImges"></u--image>
              <u--image v-else width="88px" height="88px" src="/static/goods_default_square.png"></u--image>
              
              <view class="goods-body">
                <!-- 商品名称 -->
                <view class="goods-name">
                  <u--text size="28rpx" :lines="2" :text="item.exhibitionName"></u--text>
                </view>
                <!-- 价格和数量 -->
                <view class="price-number">
                  <view class="pn-price">
										<!-- 券后价 -->
										<view class="pnp-useCoupon" v-if="item.useCouponPrice">
											<view class="pnpu-top">
												<text class="symbol">¥</text>
												<text>{{ formatMoney(item.price) }}</text>
											</view>
											<view class="pnpu-bottom">
												<text class="pnpub-text">券后价</text>
												<text class="symbol">¥</text>
												<text>{{ formatMoney(item.useCouponPrice) }}</text>			
											</view>
										</view>
										<!-- 促销价 -->
										<view class="pnp-origin" v-else>
											<text class="symbol">¥</text>
											<text>{{ formatMoney(item.price) }}</text>
										</view>
                  </view>
                  <view class="pn-number">
                   <uni-number-box
                      :min="1"
                      v-model="item.quantity"
                      @change="updateNumber(item)">
                    </uni-number-box>
                  </view>
                </view>
              </view>
            </view>
            
            <!-- 右侧操作 -->
            <template v-slot:right>
              <view class="right-action">
                <view class="ra-item btn-delete" @click="onRemove(item)"><text>删除</text></view>
              </view>
            </template>
          </uni-swipe-action-item>
        </uni-swipe-action>
        
      </scroll-view>
      
      <!-- 购物车底部操作 -->
      <view class="cart-cashier">
        <view class="cc-check-all">
          <u-checkbox-group v-model="checkedAll" @change="onCheckAll">
          	<u-checkbox
              name="all"
              size="18px"
              icon-size="14px"
              label-size="14px"
              shape="circle"
              label="全选">
            </u-checkbox>
          </u-checkbox-group>
        </view>
        <view class="total">
          <text>商品总价：</text>
          <view class="t-price">
            <text class="symbol">¥</text>
            <text>{{ formatMoney(totalAmount) }}</text>
          </view>
        </view>
        <view class="btn-submit" @click="toConfirmOrder">去结算</view>
      </view>
    </view>
    <view class="cart-empty" v-else  :style="{marginTop: `${getSystemInfo.navBarHeight}px`}">
      <cover-image class="image" src="/static/empty2.png"></cover-image>
      <view class="text">
        <text>购物车空空如也</text>
        <text>去挑选合适的轮胎吧</text>
      </view>
    </view>
    
    <u-modal :show="visibleModal" ref="uModal" :asyncClose="true"></u-modal>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
  import { formatMoney } from '@/common/utils'
  import navagationBar from '@/components/navigationBar.vue'
  import navBar from '@/components/navBar.vue'
  import { mapGetters } from 'vuex'
  
  export default {
    name: 'cart-list',
    components: {
      navBar
    },
    props: {
      isComponent: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        // 商品列表
        goodsList: [],
        
        // 全选 选中['all']
        checkedAll: [],
        
        // 选中商品id
        checkedIds: [],
        
        // 购物车是否有商品，此字段通过接口确定（用于显示缺省图）
        hasGoods: true,
        
        // 对话框显隐
        visibleModal: false,
        
        // 来源（跳转购物车之前的页面）
        // path: 上一页路径；isTabbar: 上一页是否是tabbar
        source: {
          path: '',
          isTabbar: true
        },
				
				// 优惠券列表
				couponList: [],
				
				// 轮胎商品id列表
				tyreGoodsList: 0
      }
    },
    computed: {
      ...mapGetters('global', ['getSystemInfo']),
			...mapGetters('user', ['getUserInfo']),
      
      // 是否子页
      isSubPage() {
        return !this.isComponent && !!this.source.path
      },
      
      // 已选商品
      checkedGoods() {
        return this.goodsList.filter(goods => {
          return Array.isArray(goods.checked) && goods.checked[0] === goods.goodsId
        })
      },
      // 是否全选中
      isCheckedAll() {
        return this.goodsList.every(goods => {
          return Array.isArray(goods.checked) && goods.checked[0] === goods.goodsId
        })
      },
      // 合计金额
      totalAmount() {
        const total = this.checkedGoods.reduce((acc, cur) => {
          const { price, quantity } = cur
					acc += (parseFloat(price) || 0) * (quantity || 1)
          return acc
        }, 0)
				let reductionAmount = 0
				let checkGoodsNum = this.checkedGoods.reduce((pre, cur) => {
					// 优惠券累计得是轮胎商品
					if(this.tyreGoodsList.includes(cur.goodsId)){
						pre += cur.quantity
					}
					return pre
				}, 0)
				// 自动选取优惠券
				// 1、选取的优惠券总数量不能超过轮胎总数，
				this.couponList.slice(0, checkGoodsNum).forEach(item => {
						reductionAmount += item.denomination // 当前累加
				})
				
        return total - reductionAmount
      },
    },
    methods: {
			// 使用商品id获取商品类型
			async getGoodsType() {
			  const goodIds = this.goodsList.map(item => item.goodsId)
			  const { datas } = await this.$request({
			    url: '/product-center/supply-chain-goods/checkGoodsTypeByGoodId',
			    data: { goodIds }
			  })
			  
			  // 过滤轮胎商品 - 获取可用优惠券
				this.tyreGoodsList = datas.tyreList
				this.getConponList()
			},
			// 获取优惠券列表
			async getConponList(){
				const res = await this.$request({
					url: '/marketing-center/distribution/listByAPP',
					data: {
						couponStatusList: ["0"],
						pageSize: 10000,
						pageNum: 1,
						userId: this.getUserInfo.id,
						goodIds: this.tyreGoodsList
					}
				})
				this.couponList = res.datas.data
			},
      // 获取购物车商品列表
      async getGoodsList() {
        try {
          const { datas } = await this.$request({
            url: '/order-center/owner-carts/list',
            method: 'GET',
            data: {
              pageNum: 1,
              pageSize: 1000
            }
          })
          this.hasGoods = datas.data.length > 0
          const goodsList = datas.data.map(item => {
            const isChecked = this.checkedIds.includes(item.goodsId)
            item.checked = isChecked ? [item.goodsId] : []
            return item
          })
					
          this.$set(this, 'goodsList', goodsList)
					
					this.getGoodsType()
        } catch (err) {
          this.hasGoods = false
          this.$refs.uToast.show({
            message: err.respMsg  || '请求失败',
            position: 'top'
          })
        }
      },
      
      // 修改商品数量
      async updateNumber(goods) {
        await this.$nextTick()
        const { goodsId, quantity } = goods
        this.$request({
          url: '/order-center/owner-carts/addOrUpdate',
          data: {
            goodsContexts: [
              { goodsId, quantity }
            ]
          }
        })
      },
      
      // 删除商品
      async onRemove(goods, index) {
        const { goodsId, quantity } = goods
        try {
          // 接口删除此商品
          await this.$request({
            url: '/order-center/owner-carts/delete',
            data: {
              goodsContexts: [
                { goodsId, quantity }
              ]
            }
          })
          this.getGoodsList()
        } catch (err) {
          this.$refs.uToast.show({
            message: err.respMsg || '删除失败',
            position: 'top'
          })
        }
      },
      
      // 跳转确认订单页
      toConfirmOrder() {
        if (this.checkedGoods.length === 0) {
          uni.showToast({
            title: '未选择商品',
            icon: 'error'
          })
          return
        }
        uni.navigateTo({
          url: '/cartPack/confirmOrder/confirmOrder',
          success: (res) => {
            const data = this.checkedGoods
            res.eventChannel.emit('confirmOrder', {
              sourceType: 'CART', // 申明来自购物车。CART=购物车，GOOD_DETAIL=商品详情
              data
            })
          }
        })
      },
      
      // 选择单个checkbox
      onCheckItem(id) {
        const index = this.checkedIds.findIndex(item => item === id)
        if (index === -1) {
          // 选中
          this.checkedIds.push(id)
        } else {
          // 取消
          this.checkedIds.splice(index, 1)
        }
      },
      
      // 全选
      onCheckAll(checked) {
        if (checked[0] === 'all') {
          const ids = this.goodsList.map(goods => {
            this.$set(goods, 'checked', [goods.goodsId])
            return goods.goodsId
          })
          this.checkedIds = ids
        } else {
          this.goodsList.forEach(goods => {
            goods.checked = []
            this.checkedIds = []
          })
        }
      },
      
      // 返回上一页
      toBack() {
        if (this.isSubPage) {
          const { path, isTabbar } = this.source
          if (isTabbar) {
            uni.switchTab({ url: path })
          } else {
            uni.navigateBack()
          }
					
					// 上报
					this.$uma.trackEvent('view');
					this.autoReport({
						pageName: '购物车',
						eventCode: 'view',
						eventDuration: this.diffTime()
					})
        }
      },
      // 返回首页
      toHome() {
        uni.switchTab({ url: '/pages/index/index/index' })
      },
      
      // 设置tabbar购物车
      setTabbarCart() {
        this.getGoodsList()
        
        // 重置页面为一级页
        this.source = {
          path: '',
          isTabbar: true
        }
      },
      
      formatMoney,
    },
    onShow() {
      this.getGoodsList()
			
			// 设置上报开始时间
			this.setStartTime()
    },
		onHide(){
			// 上报
			this.$uma.trackEvent('view');
			this.autoReport({
				pageName: '购物车',
				eventCode: 'view',
				eventDuration: this.diffTime()
			})
		},
    created() {
      uni.$on('cartSource', (data) => {
        this.source = {
          path: data.path,
          isTabbar: data.isTabbar
        }
      })
    },
		// 点击tabBar把当前的下标传入全局
		onTabItemTap(item) {
			this.$store.state.global.tabBarIndex = item.index
		},
    watch: {
      isCheckedAll(isChecked) {
        this.checkedAll = isChecked ? ['all'] : []
      }
    }
  }
</script>

<style scoped lang="scss">
.cart {
  .nav-only-title {
    /deep/ .nav-bar {
      right: 7px;
    }
    /deep/ .a-title {
      position: absolute !important;
      transform: translateX(-50%);
    }
  }
  
  .cart-content {
    display: flex;
    flex-direction: column;
    height: 100vh;
  }
  .cart-empty {
    
  }
  .list {
    flex: 1;
    padding: 0 20rpx;
    height: calc(100% - 100rpx);
    box-sizing: border-box;
  }
  
  /deep/ .uni-swipe {
    background-color: #fff;
  }
  
  .cart-item {
    display: flex;
    flex-direction: row;
    gap: 20rpx;
    padding: 24rpx 0;
    margin: 0 20rpx;
    border-bottom: 1px solid rgba(0, 0, 0, 0.08);
    font-size: 28rpx;
    
    .ci-checkbox {
      display: flex;
      justify-content: space-between;
      align-items: center;
      /deep/.u-checkbox-group {
        flex: 1;
        .u-checkbox__icon-wrap {
          margin: 0 !important;
        }
      }
    }
    .goods-body {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .goods-name {
        flex: 0 !important;
        /deep/.u-text{
          text-shadow: 0 0 0.1px currentcolor;
        }
      }
    }
    .price-number {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      .pn-price {
        color: $uni-primary;
				display: flex;
				flex-direction: column;
        .symbol {
          font-size: 22rpx;
          margin-right: 2px;
        }
				.pnp-useCoupon {
					.pnpu-top {
						// font-size: 36rpx;
					}
				}
				.pnpu-bottom {
					font-size: 22rpx;
					background-color: rgba(238, 59, 59, .1);
					border-radius: 4rpx;
					padding: 4rpx 6rpx;
					box-sizing: border-box;
					.pnpub-text {
						display: inline-block;
						margin-right: 6rpx;
					}
				}
      }
    }
  }
  
  .right-action {
    display: flex;
    width: 70px;
    .ra-item {
      display: flex;
      flex: 1;
      justify-content: center;
      align-items: center;
    }
    .btn-delete {
      background-color: $uni-primary;
      color: #fff;
    }
  }
  
  .cart-cashier {
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: row;
    height: 130rpx;
    padding: 10rpx 20rpx 40rpx;
    background-color: #fff;
    .cc-check-all {
      // padding: 0 0 0 20rpx;
    }
    .total {
      flex: 1;
      display: flex;
      flex-direction: row;
      padding: 0 10rpx 0 30rpx;
      font-size: 28rpx;
      color: rgba(0, 0, 0, 0.65);
      .t-price {
        color: $uni-primary;
        .symbol {
          font-size: 22rpx;
          margin-right: 2px;
        }
      }
    }
    .btn-submit {
      width: 210rpx;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 6rpx;
      text-align: center;
      color: #fff;
      background-color: $uni-primary;
    }
  }
  
  .cart-empty {
    padding: 275rpx 0 0;
    text-align: center;
    .image {
      width: 440rpx;
      height: 360rpx;
      margin: 0 auto 18rpx;
    }
    .text {
      display: flex;
      flex-direction: column;
      justify-content: center;
      font-size: 28rpx;
      line-height: 2;
      color: rgba(0, 0, 0, 0.3);
    }
  }
  
  .cart-component-content {
    .list {
      height: calc(100% - 130rpx);
    }
    .cart-cashier {
      height: 100rpx;
      padding: 10rpx 20rpx;
    }
  }
}
</style>
